import React, { useEffect, useState } from 'react'
import { Card, Form, Button, Input, Select, Table, Row, Col, message } from 'antd'
import { SearchOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons"
import { useNavigate } from 'react-router-dom'


import {
  getHospitalListRequest,
  getProvinceRequest,
  getCityOrDistriCtRequest,
  changeStatusRequest
} from '@/api/hospital/hospitalList'

import type {
  getHosListSearchParamsType,
  hospitalListContentType,
  hospitalListItemsType,
  getProvinceReturnType
} from '@/api/hospital/model/hospitalListType'


export default function HospitalList() {
  const navigate = useNavigate()

  const [form] = Form.useForm()
  //控制表格是否加载中的状态
  const [isLoading, setIsLoading] = useState(false)
  //控制当前页码的状态
  const [page, setPage] = useState(1)
  //控制每页显示的条数
  const [limit, setLimit] = useState(3)
  //控制医院总数量
  const [total, setTotal] = useState(0)
  //控制查询时用户输入的表单参数
  const [searchParams, setSearchParams] = useState<getHosListSearchParamsType>({})
  //控制表格的数据
  const [hospitalList, setHospitalList] = useState<hospitalListContentType>([])
  //控制省份的状态
  const [province, setProvince] = useState<getProvinceReturnType>([])
  //控制市的数据
  const [cityList, setCityList] = useState<getProvinceReturnType>([])
  //控制区的数据
  const [district,setDistrict]  = useState<getProvinceReturnType>([])
  //控制医院类型
  const [hospitalType,setHospitalType] = useState<getProvinceReturnType>([])
  //控制重新渲染的state
  const [reRender,setReRender] = useState(true)


  //1.刚加载组件的时候,发送医院列表的请求
  useEffect(() => {

    const getHospitalList = async () => {
      setIsLoading(true)

      const result = await getHospitalListRequest(page, limit, searchParams)
      //把结果中的医院列表的数组设置给状态state
      setHospitalList(result.content)

      //把结果中的医院总数设置给状态state
      setTotal(result.totalElements)

      setIsLoading(false)
    }

    getHospitalList()
  }, [searchParams,page,limit,reRender])

  //2.初始化的时候请求所有的省份
  useEffect(() => {
    const getProvince = async () => {
      const result = await getProvinceRequest()
      // console.log(result);
      //把得到的省份列表放到state中
      setProvince(result)

    }
    getProvince()
  }, [])

  //3.初始化的时候立即请求医院类型
  useEffect(()=>{
    const getHospitalType = async ()=>{
      const result = await getCityOrDistriCtRequest('10000')

      //把医院类型设置给状态
      setHospitalType(result)
    }
    getHospitalType()
  },[])


  //事件回调函数
  //1.选择省份的时候的事件回调函数
  const changeProviceHandle = async (value: string) => {
    //根据省份的value 发送市的请求
    const result = await getCityOrDistriCtRequest(value)
    //把结果交给state
    setCityList(result)

    //选择完省份的时候,把市和区目前的value清除掉
    form.setFieldsValue({cityCode:null,districtCode:null})
    //清除区/县的数据
    setDistrict([])
  }

  //2.选择城市的时候事件回调函数
  const cityChangeHandle = async (value: string) => {
    //根据市的value 发送市的请求
    const result = await getCityOrDistriCtRequest(value)
    //把结果交给state
    setDistrict(result)

    //选择完市的时候,把区目前的value清除掉
    form.setFieldsValue({districtCode:null})
  }

  //3.查询表单的提交事件
  const finishHandle = (value:getHosListSearchParamsType)=>{
    // console.log(value);
    
    setSearchParams(value)
  }

  //4.点击查询表单的清空按钮
  const clearSearchHandle = ()=>{
    setSearchParams({})
  }

  //5.点击查询按钮事件回调函数
  const hospitalDetailHandle = (id:string)=>{
    return ()=>{
      navigate(`/syt/hospital/hospitalShow/${id}`,{
        //测试state传值(练习)
        state:{hello:'你好'}
      })

    }
  }

  //6.点击上下线的事件回调函数
  const changeStateHandle = (id:string,status:0|1)=>{
    return async ()=>{
      await changeStatusRequest(id,status)

      message.success('改变医院上下线状态成功')

      //重新渲染
      setReRender(!reRender)
    }
  }

  //7.点击排版规则
  const showScheduleHandle = (hoscode:string)=>{
    return ()=>{
      navigate(`/syt/hospital/hospitalSchedule/${hoscode}`)
    }
  }



  //表格的字段
  const columns = [
    {
      title: '序号',
      width: 60,
      dataIndex: 'index',
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      //如果设置了dataIndex,则render拿到的时dataIndex对应的数据
      title: '医院logo',
      dataIndex: 'logoData',
      render(logoData: string) {
        return (
          //图片前面要拼接data:image/jpeg;base64
          <img width={100} src={`data:image/jpeg;base64,${logoData}`} alt="" />
        )
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      //如果没有dataIndex设置,则render中拿到的数据就是当前完整的数据
      title: '等级',
      render(_: any, data: hospitalListItemsType) {
        return data.param.hostypeString
      }
    },
    {
      title: '详细地址',
      render(_: any, data: hospitalListItemsType) {
        return data.param.fullAddress
      }
    },
    {
      title: '状态',
      render(_: any, data: hospitalListItemsType) {
        return data.status === 0 ? '下线' : '上线'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      width: 120,
      fixed: "right" as "right",
      // dataIndex: "id",
      render(_:any,data:hospitalListItemsType) {
        // console.log(id);
        
        return (
          <div>

            <Button type='primary' onClick={hospitalDetailHandle(data.id)}>查看</Button>
            <Button type='primary' onClick={showScheduleHandle(data.hoscode)}>排班</Button>
            <Button type='primary' onClick={changeStateHandle(data.id,data.status === 0?1:0)} >{data.status === 0?'上线':'下线'}</Button>


          </div >
        )
      }
    }
  ];
  return (
    <div>
      <Card>
        <Form
          name="basic"
          form={form}
          onFinish={finishHandle}
        >
          <Row gutter={15}>
            <Col span={4}>
              <Form.Item
                name="provinceCode"
              >
                <Select
                  placeholder="请输入省份"
                  allowClear
                  onChange={changeProviceHandle}
                >
                  {
                    province.map(
                      item => {
                        return (
                          <Select.Option key={item.id} value={item.value}>{item.name}</Select.Option>

                        )
                      })}

                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="cityCode"
              >
                <Select
                  placeholder="请输入市"
                  allowClear
                  onChange={cityChangeHandle}
                >
                  {
                    cityList.map(
                      item => {
                        return (
                          <Select.Option key={item.id} value={item.value}>{item.name}</Select.Option>

                        )
                      })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="districtCode"
              >
                <Select
                  placeholder="请输入县/区"
                  allowClear
                >{
                  district.map(
                    item => {
                      return (
                        <Select.Option key={item.id} value={item.value}>{item.name}</Select.Option>

                      )
                    })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="hosname"
              >
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="hoscode"
              >
                <Input placeholder='医院编号' />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="hostype"
              >
                <Select
                  placeholder="医院类型"
                  allowClear
                >
                  {
                    hospitalType.map(
                      item => {
                        return (
                          <Select.Option key={item.id} value={item.value}>{item.name}</Select.Option>

                        )
                      })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={15}>
            <Col span={4}>
              <Form.Item
                name="status"
              >
                <Select
                  placeholder="医院状态"
                  allowClear
                >
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />} >
                  查询
                </Button>
              </Form.Item>
            </Col>


            <Col span={2}>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="default" htmlType="reset" onClick={clearSearchHandle}>
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Table
          columns={columns}
          dataSource={hospitalList}
          scroll={{ x: 1100 }}
          //在toble中 要求dataSouurce中有key属性,大多数如果真的没有key 则可以使用rowkey属性指定dataSource中的一个属性作为key
          rowKey='id'
          //页面是否加载中
          loading={isLoading}
          //显示边框线
          bordered

          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total: total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [2, 3, 4, 5],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            //用于显示数据总量和当前数据顺序
            showTotal(total) {
              return `总共有${total}条数据`
            },

            //页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
            onChange (page:number,pageSize:number){
              setPage(page);
              setLimit(pageSize);
            }
          }}
        />;
      </Card>
    </div>
  )
}
